package root.electronclass.electronclass.grade.homework

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.widget.ListPopupWindow
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.forEachIndexed
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.viewModels
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.databinding.FragmentClassHomeworkDetailBinding
import root.electronclass.electronclass.databinding.FragmentClassHomeworkDetailItemBinding
import root.electronclass.electronclass.ext.doOnSearch
import root.electronclass.electronclass.ext.dp
import root.electronclass.electronclass.grade.homework.viewmodel.ClassHomeworkDetailViewModel
import root.electronclass.electronclass.grade.model.ClassHomeworkItem
import root.electronclass.electronclass.grade.model.ClassHomeworkUser
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale

/**
 * 电子班牌-班级版-班级空间-班级作业-作业详情
 * @author Lokiy
 * @date 2023/2/18 19:11
 */
class ClassHomeworkDetailFragment : ViewBindingFragment<FragmentClassHomeworkDetailBinding>() {

    private val viewModel by viewModels<ClassHomeworkDetailViewModel>()

    private val studentAdapter = BasicAdapter<ClassHomeworkUser, FragmentClassHomeworkDetailItemBinding> { holder, item ->
        holder.binding.root.backgroundTintList = ColorStateList.valueOf(if (holder.adapterPosition % 2 == 0) 0 else 0xfF7f8f9)
        holder.binding.itemName.text = item.name
        holder.binding.itemNo.text = item.userNo
        holder.binding.itemElapsed.text = getString(R.string.minute, ((item.preHour ?: 0f)).toInt())
        if (item.status == 2) {
            holder.binding.itemStatus.setText(R.string.done)
            holder.binding.itemStatus.setTextColor(resources.getColor(R.color.c_093b5d))
            holder.binding.itemCompleteTime.text = getString(R.string.minute, ((item.hour ?: 0f)).toInt())
        } else {
            holder.binding.itemStatus.setText(R.string.undone)
            holder.binding.itemStatus.setTextColor(resources.getColor(R.color.c_ff503d))
            holder.binding.itemCompleteTime.text = "-"
        }
        if (item.score.isNullOrEmpty()) {
            holder.binding.itemScore.text = "-"
            holder.binding.itemScore.setTextColor(resources.getColor(R.color.c_093b5d))
        } else {
            if (item.score.contains("-") || item.status == 1) {
                holder.binding.itemScore.text = "${item.score}分"
                holder.binding.itemScore.setTextColor(resources.getColor(R.color.c_ff503d))
            } else {
                holder.binding.itemScore.text = "+${item.score}分"
                holder.binding.itemScore.setTextColor(resources.getColor(R.color.c_093b5d))
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val detail: ClassHomeworkItem = arguments?.getParcelable(EXTRA_DATA) ?: return
        binding.detail.update(detail)
        val padding = 24.dp.toInt()
        binding.studentRecyclerTitle.root.apply {
            val names = resources.getStringArray(R.array.class_homework_detail_titles)
            forEachIndexed { index, it ->
                it as TextView
                it.setTextColor(0xFFFFFFFF.toInt())
                it.text = names[index]
            }
            updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = padding
            }
        }
        binding.detail.root.let {
            it.setBackgroundResource(R.drawable.bg_white_12)
            it.setPadding(32, padding, 32, padding)
            it.updateLayoutParams<ViewGroup.LayoutParams> {
                width = 375.dp.toInt()
            }
        }
        binding.studentRecycler.adapter = studentAdapter
        binding.status.text = getString(R.string.class_homework_status)
        binding.status.setOnClickListener {
            ListPopupWindow(requireContext()).apply {
                anchorView = it
                isModal = true
                setAdapter(
                    ArrayAdapter(
                        requireContext(),
                        android.R.layout.simple_list_item_1,
                        (0..5).map { ClassHomeworkItem.convertStatusToText(it) })
                )
                setOnItemClickListener { _, _, position, _ ->
                    if (position == 0) {
                        binding.status.text = getString(R.string.class_homework_status)
                    } else {
                        binding.status.text = ClassHomeworkItem.convertStatusToText(position)
                    }
                    dismiss()
                    viewModel.status.value = position
                }
            }.show()
        }
        binding.search.doOnSearch { key ->
            viewModel.searchKey.value = key
            true
        }

        viewModel.detail.observe(viewLifecycleOwner) {
            studentAdapter.notifyChanged(it)
        }
        viewModel.complete.observe(viewLifecycleOwner) {
            val decimalFormat = DecimalFormat("0.##", DecimalFormatSymbols(Locale.CHINA))
            binding.completePercent.text = getString(R.string.class_homework_complete_percent, decimalFormat.format(it))
        }
    }
}